/**
 *
   简要说明
   1.针对托盘图标的操作即对当前AIR应用的nativeApplication.icon属性的相关操作，例如bitmaps,menu属性
   2.对于Windows和Mac系统，nativeApplication.icon的实例对象是不一样的，Windows返回的是SystemTrayIcon对象，而Mac(苹果系统)返回的是DockIcon对象（这里以Windows系统为例）
   3.添加图标到系统托盘，只需要设置当前AIR应用的nativeApplication.icon.bitmaps属性，就可以在系统托盘看到图标，但是这时还没有任何事件响应，需要进一步处理
   4.添加系统托盘的左键单击事件，这种情况一般就是恢复窗口到正常状态
   为SystemTrayIcon添加MouseEvent.CLICK事件
   5.添加系统托盘图标的右键事件，这里一般是个菜单列表，例如打开、退出等。
   需要设置SystemTrayIcon的menu属性，这里需要说明的是
   6.nativeWindow.visible控制了AIR应用在任务栏上(不是系统托盘)的图标显示
 *
 */



import com.yf.alarm.count.TransferTime;
import com.yf.alarm.statics.Statics;

import component.Aboutme;

import flash.desktop.SystemTrayIcon;
import flash.display.DisplayObject;
import flash.display.NativeWindow;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.NativeWindowBoundsEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;

import mx.collections.ArrayCollection;
import mx.controls.Alert;

import spark.components.Window;




[Embed(source='assets/alarm16x16.png')]
private var icon:Class;

[Embed(source='assets/alarm1_16x16.png')]
private var icon1:Class;

[Bindable]
public var timeSelect:ArrayCollection=new ArrayCollection(Statics.timeSelectCollectionData);

private var timer:Timer=new Timer(500); //闪动频率
private var timerCounter:int=0; //闪动标记
private var timeDelay:Number=-1; //选定的延迟时间
private var timerShow:Timer=new Timer(1000); //显示计时
private var timerShowCounter:int=0; //计时计数器

private var aboutme:Aboutme=new Aboutme();

private var settingShareObject:SharedObject=SharedObject.getLocal("user-setting"); //保存用户设置



private function Main():void
{
	styles();
	addListeners();
	addObjects();
}

private function styles():void
{
	picContainer.removeElement(picContent);
	
	//窗口初始位置
	var screenWidth:int;
	var screenHeight:int;
	for each (var screen:Screen in Screen.screens)
	{
		//_txt.text = screen.bounds.width + "x" + screen.bounds.height + "Color depth:" + screen.colorDepth + "bit";
		screenWidth=screen.bounds.width;
		screenHeight=screen.bounds.height;
	}
	this.nativeWindow.x=screenWidth * Statics.positionPer;
	this.nativeWindow.y=(screenHeight - this.nativeWindow.height) / 2;

	mainPanelTitle.title=Statics.timeAlarmTitle;

	minBtn.toolTip=Statics.minBtnToolTip;
	closeBtn.toolTip=Statics.closenBtnToolTip;

	if (settingShareObject.data.userSetting_startAtLogin)
	{
		startAtLoginCB.selected=true;
	}
	else
	{
		startAtLoginCB.selected=false;
	}

	initializationStyle();


}

private function addListeners():void
{
	addEventListener(MouseEvent.MOUSE_DOWN, dragHandler); //窗口拖拽
	minBtn.addEventListener(MouseEvent.CLICK, minHandler); //最小化程序
	closeBtn.addEventListener(MouseEvent.CLICK, closeHandler); //退出

	this.nativeWindow.addEventListener(Event.RESIZE, resizeHandler);//监听全屏变化
}

private function addObjects():void
{
	addSysTrayIcon(); //添加任务栏图标
}


//status

private function initializationStyle():void
{
	confirmBtn.mouseEnabled=false;
	confirmBtn.alpha=.5;
	resetBtn.mouseEnabled=false;
	resetBtn.alpha=.5;

	countLabel.text=Statics.countTextInit;
	flashingLabel.text="";

	cb.enabled=true;

	this.nativeApplication.icon.bitmaps=[new icon()];
	timerCounter=0;

	if(picContainer.numElements>0)picContainer.removeElement(picContent);
	
}

private function preparativeStyle():void
{
	confirmBtn.mouseEnabled=true;
	confirmBtn.alpha=1;
	resetBtn.mouseEnabled=false;
	resetBtn.alpha=.5;

	countLabel.text=Statics.countTextInit;

	cb.enabled=true;
}

private function countStyle():void
{
	confirmBtn.mouseEnabled=false;
	confirmBtn.alpha=.5;
	resetBtn.mouseEnabled=true;
	resetBtn.alpha=1;

	cb.enabled=false;
}

private function flashingStyle():void
{
	confirmBtn.mouseEnabled=false;
	confirmBtn.alpha=.5;
	resetBtn.mouseEnabled=true;
	resetBtn.alpha=1;

	countLabel.text=Statics.countTextInit;
	flashingLabel.text=Statics.flashingText;
	
	undockHandler();

	//全屏
	stage.displayState=StageDisplayState.FULL_SCREEN_INTERACTIVE;
	
	this.nativeWindow.orderToFront();

}



// //status



//系统任务栏

//1.最小化事件时添加创建系统托盘图标， 可直接添加到一个按钮的CLICK事件来测试
//最小化到系统托盘处理

private function addSysTrayIcon():void
{
	//icon16是一个图片文件，大小为16*16
	this.nativeApplication.icon.bitmaps=[new icon()];
	if (NativeApplication.supportsSystemTrayIcon)
	{
		var sti:SystemTrayIcon=SystemTrayIcon(this.nativeApplication.icon);
		//创建菜单列表
		sti.menu=createSysTrayMenu();
		sti.addEventListener(MouseEvent.CLICK, restoreFromSysTrayHandler); //左键点击系统任务栏图标
		sti.tooltip=Statics.timeAlarmTitle;
	}

}




//2.创建系统托盘图标上下文菜单
private function createSysTrayMenu():NativeMenu
{
	var menu:NativeMenu=new NativeMenu();
	var labels:Array=[Statics.menuItemOpen, Statics.menuItemAbout, "", Statics.menuItemExit];
	var names:Array=[Statics.menuOpen, Statics.menuAbout, Statics.menuSeparator, Statics.menuExit];
	for (var i:int=0; i < labels.length; i++)
	{
		//如果标签为空的话，就认为是分隔符
		var menuItem:NativeMenuItem=new NativeMenuItem(labels[i], labels[i] == "");
		menuItem.name=names[i];
		menuItem.addEventListener(Event.SELECT, sysTrayMenuHandler); //菜单处理事件
		menu.addItem(menuItem);
	}

	return menu;
}

//3.添加系统托盘菜单事件，根据菜单名称来处理
private function sysTrayMenuHandler(event:Event):void
{
	switch (event.target.name)
	{
		case Statics.menuOpen: //打开菜单
			undockHandler();
			break;
		case Statics.menuAbout: //关于
			aboutMeHandler();
			break;
		case Statics.menuExit: //退出菜单
			exitHandler();
			break;
	}

}

//4.从系统托盘恢复到任务栏
private function undockHandler():void
{
	this.nativeWindow.visible=true;
	//this.nativeApplication.icon.bitmaps=[new icon()];
	//窗口提到最前面
	this.nativeWindow.orderToFront();
	//激活当前窗口
	this.activate();
}


//关于
private function aboutMeHandler():void
{
	undockHandler();

	aboutme.addEventListener(Statics.CLOSE_WINDOW, closeAboutHandler);
	addElement(aboutme);
}

private function closeAboutHandler(event:Event):void
{
	aboutme.removeEventListener(Statics.CLOSE_WINDOW, closeAboutHandler);
	removeElement(aboutme);
}


//5.退出程序的菜单事件
private function exitHandler():void
{
	this.exit();
}


private function restoreFromSysTrayHandler(event:MouseEvent):void //最大最小化
{
	
	/*if (nativeWindow.displayState == NativeWindowDisplayState.NORMAL)
	{
		minimize();
		nativeWindow.visible=false;
	}
	else if (nativeWindow.displayState == NativeWindowDisplayState.MINIMIZED)
	{
		undockHandler();
	}
	else if (nativeWindow.displayState == NativeWindowDisplayState.MAXIMIZED)
	{
		minimize();
		nativeWindow.visible=false;
	}*/
	
	if (nativeWindow.displayState == NativeWindowDisplayState.MINIMIZED)
	{
		undockHandler();
	}
	else
	{
		minimize();
		nativeWindow.visible=false;
		
		if(picContainer.numElements>0)picContainer.removeElement(picContent);
	}
}



// //系统任务栏









//闪动
private function flash():void
{
	flashingStyle();

	timer.addEventListener(TimerEvent.TIMER, timerCompleteHandler);
	timer.start();//闪动

	if(picContainer.numElements<1)picContainer.addElement(picContent);
}

private function timerCompleteHandler(event:TimerEvent):void
{
	if (timerCounter == 1)
	{
		this.nativeApplication.icon.bitmaps=[new icon()];
		timerCounter=0;

		flashingLabel.text="";
	}
	else if (timerCounter == 0)
	{
		this.nativeApplication.icon.bitmaps=[new icon1()];
		timerCounter=1;

		flashingLabel.text=Statics.flashingText;
	}
	timer.start();
}

private function resizeHandler(event:Event):void //全屏变化处理
{

	//窗口宽，判断是否全屏用
	var screenWidth:int;
	for each (var screen:Screen in Screen.screens)screenWidth=screen.bounds.width;


	if (this.stage.nativeWindow.width == screenWidth) //全屏
	{ 
		flashingLabel.scaleX=flashingLabel.scaleY=5;
		this.nativeWindow.orderToFront();
	}
	else //非全屏
	{ 
		flashingLabel.scaleX=flashingLabel.scaleY=1;
	}

}






private function dragHandler(event:MouseEvent):void //拖拽
{
	this.stage.nativeWindow.startMove();
}

private function minHandler(event:MouseEvent):void //最小化
{
	flashingLabel.scaleX=flashingLabel.scaleY=1;

	this.minimize();
	nativeWindow.visible=false;
	
	if(picContainer.numElements>0)picContainer.removeElement(picContent);
	
}

private function closeHandler(event:MouseEvent):void //x退出
{
	exitHandler();
}










//计时

private function cbHandler(event:Event):void //下拉框选定
{
	/*
	   test.text="You selected: " + ComboBox(event.target).selectedItem.label; //targht是event事件的目标;ComboBox具有selectedItem属性
	   test1.text="Data: " + ComboBox(event.target).selectedItem.data;
	 */

	timeDelay=ComboBox(event.target).selectedItem.data; //秒
	if (timeDelay > 0)
	{
		preparativeStyle();
	}
	else if (timeDelay < 0)
	{
		initializationStyle();
	}
}

private function confirmBtnHandler(event:MouseEvent):void //确认
{
	if (timeDelay < 0)
	{
		Alert.show(Statics.selectTimeFailAlert);
	}
	else
	{
		calculagraph();
	}

	countStyle();
}

private function resetBtnHandler(event:MouseEvent):void //重置
{
	timer.stop();

	cb.selectedIndex=0;

	timerShow.stop();
	timerShowCounter=0;

	//取消全屏
	stage.displayState=StageDisplayState.NORMAL;

	initializationStyle();
}



private function calculagraph():void
{
	timerShowCounter=timeDelay;
	timerShow.addEventListener(TimerEvent.TIMER, timerShowHandler);
	timerShow.start();
}

private function timerShowHandler(event:TimerEvent):void
{
	timerShowCounter-=1;
	countLabel.text=TransferTime.transferTimeHandler(timerShowCounter * 1000);

	if (timerShowCounter == 0)
	{
		timerShow.stop();
		flash(); //开始提醒
	}
}





//setting

//开机启动
private function startAtLoginCBClickHandler(event:MouseEvent):void //点击CheckBox
{
	if (CheckBox(event.target).selected)
	{
		settingShareObject.data.userSetting_startAtLogin=true;
	}
	else
	{
		settingShareObject.data.userSetting_startAtLogin=false;
	}

	saveSetting();

}

private function saveSetting():void
{
	var flushStatus:String=null;
	try
	{
		flushStatus=settingShareObject.flush(10000);
	}
	catch (error:Error)
	{
		//Alert.show("Error...Could not write SharedObject to disk\n");
		Alert.show(Statics.setttingSaveFail);
	}
	if (flushStatus != null)
	{
		switch (flushStatus)
		{
			case SharedObjectFlushStatus.PENDING:
				//Alert.show("Requesting permission to save object...\n");
				settingShareObject.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
				break;
			case SharedObjectFlushStatus.FLUSHED:
				//Alert.show("Value flushed to disk.\n");

				doStartAtLogin();

				break;
		}
	}

}

private function onFlushStatus(event:NetStatusEvent):void
{
	//Alert.show("User closed permission dialog...\n");
	switch (event.info.code)
	{
		case "SharedObject.Flush.Success":
			//Alert.show("User granted permission -- value saved.\n");
			doStartAtLogin();
			break;
		case "SharedObject.Flush.Failed":
			//Alert.show("User denied permission -- value not saved.\n");
			Alert.show(Statics.setttingSaveFail);
			break;
	}

	settingShareObject.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
}

private function doStartAtLogin():void
{
	if (settingShareObject.data.userSetting_startAtLogin)
	{
		NativeApplication.nativeApplication.startAtLogin=true;
	}
	else
	{
		NativeApplication.nativeApplication.startAtLogin=false;
	}
}




// //setting








